import styles from './index.module.scss';
import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';
import { useParams } from 'react-router-dom';
import { useEffect, useRef, useState } from 'react';
import {
  clearDetailAction,
  followByIdAction,
  getDetailByIdAction,
} from '@/store/action/article';
import { useAppDispatch, useAppSelector } from '@/store';
import dayjs from 'dayjs';
import { sanitize } from 'dompurify';
import Skeleton from '@/components/Skeleton';

import hljs from 'highlight.js';
import 'highlight.js/styles/vs2015.css';
import classnames from 'classnames';
import NoComment from './components/NoComment';
import CommentItem from './components/CommentItem';
import { clearCommentsAction, getCommentsByIdAction } from '@/store/action/comment';
import { map } from 'lodash';
import CommentFooter from './components/CommentFooter';
import { Popup } from 'antd-mobile';
import CommentReply from './components/CommentReply';
import Share from './components/Share';

export default function Article() {
  const { id } = useParams<{ id: string }>();

  const dispatch = useAppDispatch();
  const { detail } = useAppSelector((state) => state.article);
  const { commentData, originComment } = useAppSelector((state) => state.comment);

  const [authVisible, setAuthVisible] = useState(false);
  const [shareVisible, setShareVisible] = useState(false);

  const warpRef = useRef<HTMLDivElement>(null);
  const authRef = useRef<HTMLDivElement>(null);
  const commentRef = useRef<HTMLDivElement>(null);

  const clickedRef = useRef(false);

  const handleShare = () => {
    setShareVisible(!shareVisible);
  };
  const handleClickComment = () => {
    const top = clickedRef.current ? 0 : commentRef.current!.offsetTop - 46;

    warpRef.current!.scrollTo({
      top,
      behavior: 'smooth',
    });

    clickedRef.current = !clickedRef.current;
  };

  useEffect(() => {
    dispatch(getDetailByIdAction(id));
    dispatch(getCommentsByIdAction(id, 'a'));
    return () => {
      dispatch(clearDetailAction());
      dispatch(clearCommentsAction());
    };
  }, [dispatch, id]);

  useEffect(() => {
    if (!detail.art_id) return;

    hljs.configure({
      ignoreUnescapedHTML: true,
    });

    const codes = document.querySelectorAll<HTMLElement>('.dg-thml code');
    codes.forEach((item) => {
      hljs.highlightElement(item);
    });

    const pres = document.querySelectorAll<HTMLPreElement>('.dg-html pre');
    pres.forEach((item) => {
      hljs.highlightElement(item);
    });
  }, [dispatch, detail]);

  useEffect(() => {
    const srcollFn = () => {
      const authDom = authRef.current;
      if (!authDom) return;

      const { top } = authRef.current?.getBoundingClientRect();
      if (top < 10) {
        setAuthVisible(true);
      } else {
        setAuthVisible(false);
      }
    };

    warpRef.current?.addEventListener('scroll', srcollFn);
    const warpDom = warpRef.current;
    return () => {
      warpDom?.removeEventListener('scroll', srcollFn);
    };
  }, []);

  const handleFollow = async () => {
    await dispatch(followByIdAction(detail.aut_id));
    dispatch(getDetailByIdAction(id));
  };

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        <NavBar right={<Icon type="icongengduo" />}>
          {authVisible && (
            <div className="nav-author">
              <img src={detail.aut_photo} alt="" />
              <span className="name">{detail.aut_name}</span>
              <span
                className={classnames('follow', detail.is_followed ? 'followed' : '')}
                onClick={handleFollow}
              >
                {detail.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>

        <div className="wrapper" ref={warpRef}>
          {!detail.art_id ? (
            <Skeleton />
          ) : (
            <div className="article-wrapper">
              <div className="header">
                <h1 className="title">{detail.title}</h1>

                <div className="info">
                  <span>{dayjs(detail.pubdate).format('YYYY-MM-DD')}</span>
                  <span>{detail.read_count} 阅读</span>
                  <span>{detail.comm_count} 评论</span>
                </div>

                <div className="author" ref={authRef}>
                  <img src={detail.aut_photo} alt="" />
                  <span className="name">{detail.aut_name}</span>
                  <span onClick={handleFollow} className="follow">
                    {detail.is_followed ? '已关注' : '关注'}
                  </span>
                </div>
              </div>

              <div className="content">
                <div
                  className="content-html dg-html"
                  dangerouslySetInnerHTML={{
                    __html: sanitize(detail.content),
                  }}
                />
                <div className="date">发布文章时间：{dayjs().from(detail.pubdate)}</div>

                <div className="divider"></div>
                <div ref={commentRef} className="comment">
                  <div className="comment-header">
                    <span>全部评论（{detail.comm_count}）</span>
                    <span>{detail.like_count} 点赞</span>
                  </div>
                  {detail.comm_count === 0 ? (
                    <NoComment />
                  ) : (
                    <div className="comment-list">
                      {map(commentData.results, (item) => (
                        <CommentItem key={item.com_id} comment={item} />
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
      <CommentFooter
        handleShare={handleShare}
        detail={detail}
        handleClickComment={handleClickComment}
      />

      <Popup position="right" visible={!!originComment.com_id} destroyOnClose>
        <CommentReply />
      </Popup>
      <Popup bodyStyle={{ backgroundColor: 'transparent' }} visible={shareVisible}>
        <Share handleShare={handleShare} />
      </Popup>
    </div>
  );
}
